package com.huifai.controller;


import com.alibaba.fastjson.JSONObject;
import com.huifai.common.cache.RedisService;
import com.huifai.common.constant.ERespCode;
import com.huifai.common.constant.SysConstant;
import com.huifai.vo.request.LoginUserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class BaseApp {

    private static final Logger LOGGER = LoggerFactory.getLogger(BaseApp.class);
    @Autowired
    private RedisService redisService;

    protected Map<String, Object> buildResponse() {
        return buildResponse(ERespCode.SUCCESS, null);
    }

    /**
     * 封装请求成功响应
     * 
     * @param data
     * @return
     */
    protected Map<String, Object> buildResponse(Object data) {
        return buildResponse(ERespCode.SUCCESS, data);
    }
    
    /**
     * 封装接口废弃响应
     * 
     * @param version
     * @param reason
     * @return
     */
    protected Map<String, Object> buildDeprecatedResponse(String version, String reason) {
        Map<String, String> data = new HashMap<>();
        data.put("expired_version", version);
        data.put("reason", reason);
        return buildResponse(ERespCode.DEPRECATED, data);
    }

    protected Map<String, Object> buildResponse(ERespCode errCode, Object data) {
        return buildResponse(errCode.code(), errCode.message(), data);
    }

    /**
     * 封装统一的响应格式
     * {
     *     "ret_code": {ret_code},
     *     "message": {message},
     *     "data": {data_object}
     * }
     * 
     * @param code
     * @param message
     * @param data
     * @return
     */
    protected Map<String, Object> buildResponse(int code, String message, Object data) {
        Map<String, Object> responseMap = new HashMap<>();
        responseMap.put("code", code);
        responseMap.put("msg", message);
        responseMap.put("data", data);
        responseMap.put("timestamp", System.currentTimeMillis());
        return responseMap;
    }

    /**
     * 获取
     * @param request
     * @return
     */
    protected  LoginUserInfo getCurrentUserInfo(HttpServletRequest request){
        Object loginUserInfo = request.getAttribute(SysConstant.CURRENT_USER);
        return JSONObject.parseObject(loginUserInfo.toString(),LoginUserInfo.class);
    }
}
